<template>
  <div class="goods-container">
    <!-- 筛选条件 -->
    <div class="filter-content">
      <div class="filter-btn">
        <div class="filter-title">
          <i class="el-icon-search"></i>
          <span class="">筛选搜索</span>
        </div>
        <div>
          <el-button size="small" @click="resetFilter">重置</el-button>
          <el-button type="primary" size="small" @click="submitFilter">查询结果</el-button>
        </div>
      </div>
      <div class="filter-form">
        <!-- 商品编号 -->
        <div class="filter-item">
          <div>
            <span>订单编号：</span>
            <el-input placeholder="请输入订单编号" v-model="orderNo"> </el-input>
          </div>
        </div>
        <!-- 收货人信息 -->
        <div class="filter-item">
          <div>
            <span>收货人：</span>
            <el-input placeholder="收货人姓名/电话" v-model="nameOrPhone"> </el-input>
          </div>
        </div>
        <!-- 订单状态 -->
        <div class="filter-item">
          <div>
            <span>订单状态：</span>
            <el-cascader v-model="selectValue" :options="selectOptions" placeholder="请选择订单状态"></el-cascader>
          </div>
        </div>
      </div>
    </div>
    <!-- 数据列表 -->
    <div class="goods-title">
      <div>
        <i class="el-icon-tickets"></i>
        <span style="margin-left: 5px">数据列表</span>
      </div>
    </div>
    <!-- 数据表格 -->
    <div class="goods-list">
      <el-table :data="tableData.list" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection"> </el-table-column>
        <el-table-column prop="id" label="编号"> </el-table-column>
        <el-table-column prop="orderNo" label="订单编号"></el-table-column>
        <el-table-column prop="createTime" label="提交时间" />
        <el-table-column prop="orderPrice" label="订单金额"> </el-table-column>
        <el-table-column prop="orderStatus" label="订单状态"> </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="router.push('/home/order/info/' + scope.row.id)">查看详情</el-button>
            <el-button size="small" type="success" :loading="scope.row.loading" @click="handleDelete(scope.row)">发货</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页导航 -->
      <div class="pagination-container">
        <div class="option-container">
          <div>
            <el-select v-model="value" placeholder="批量操作">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </div>
          <div class="btn">
            <el-button type="primary" @click="setRecommendOrNew" :loading="selectLoading">确定</el-button>
          </div>
        </div>
        <div class="pagination"><el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[5, 10, 15]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" background> </el-pagination></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import axios from '@/utils/request'
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'

// 创建路由对象
const router = useRouter()

const options = reactive([
  {
    // 下拉菜单选项
    value: 'deliver',
    label: '批量发货'
  }
])
let selectOptions = reactive([{ value: 1, label: '待发货' }])
let orderNo = ref('') // 订单编号
let nameOrPhone = ref('') // 收货人信息
let selectValue = reactive([1]) // 筛选条件选中
let tableData = reactive({ list: [] }) // 各表渲染数据
let selectLoading = ref(false)
let value = ref('') // 批量操作选中值
let total = ref(0) // 表格数据总数
let pageSize = ref(5) // 每一页显示的长度
let currentPage = ref(1) // 当前处于什么页
let multipleSelection = reactive([]) // 表格中选中的商品数据
let allOrderList = reactive([]) // 保存所有的商品数据

// 重置筛选条件
const resetFilter = () => {
  orderNo.value = ''
  nameOrPhone.value = ''
}
// 表格选中处理函数
const handleSelectionChange = (val) => {
  multipleSelection = val
}

// 处理请求到的表格数据
const dealOrderData = () => {
  for (let i = (currentPage.value - 1) * 5; i < currentPage.value * pageSize.value; i++) {
    if (allOrderList[i]) {
      const date = new Date(allOrderList[i].create_time)
      let status = allOrderList[i].order_status == 0 ? '等待买家支付' : allOrderList[i].order_status == 1 ? '等待商家发货' : allOrderList[i].order_status == 2 ? '等待买家收货' : '已完成'
      tableData.list.push({
        id: allOrderList[i].id,
        orderNo: allOrderList[i].order_id,
        createTime: date.toLocaleDateString() + ' ' + date.toLocaleTimeString(),
        orderPrice: '￥' + allOrderList[i].goods_num * allOrderList[i].goods_price,
        orderStatus: status,
        loading: false
      })
    } else {
      break
    }
  }
}
// 获取订单列表
const getOrderList = async () => {
  try {
    const data = await axios.get('/bus/deal/order/list')
    if (data.code === 0) {
      // 获取成功
      ElMessage({
        type: 'success',
        message: data.msg
      })
      total.value = data.data.length
      allOrderList = data.data
      dealOrderData()
    } else if (data.code === 403 || data.msg === '身份认证错误') {
      ElMessage({
        type: 'error',
        message: data.msg
      })
      localStorage.removeItem('bus_token')
      router.replace('/login')
    } else {
      ElMessage({
        type: 'error',
        message: data.msg
      })
    }
  } catch (err) {
    console.log(err)
    ElMessage.error(err)
  }
}

// 切换页数
const handleCurrentChange = (val) => {
  currentPage.value = val
  tableData.list = []
  // 根据当前页和每一页长度进行数据渲染
  dealOrderData()
}

// 切换每一页显示的长度
const handleSizeChange = (val) => {
  pageSize.value = val
  tableData.list = []
  // 根据当前页和每一页长度进行数据渲染
  dealOrderData()
}

// 批量发货
const setRecommendOrNew = async () => {
  // 必须选择一项
  if (value.value === '') return ElMessage({ type: 'error', message: '请选择操作选项！' })
  // 必须有商品选中
  if (multipleSelection.length === 0) return ElMessage({ type: 'error', message: '至少选择一件商品！' })
  // 创建商品id
  let ids = ''
  multipleSelection.forEach((item) => {
    ids += item.id + ','
  })
  ids = ids.slice(0, -1)
  // 创建请求参数
  let params = { ids, option: 'deliver' }
  selectLoading.value = true
  try {
    const data = await axios.post('/bus/deal/order/option', params)
    tableData.list = []
    if (data.code === 0) {
      // 更新数据成功
      ElMessage({ type: 'success', message: data.msg })

      // 重新获取订单数据
      getOrderList()
    } else {
      ElMessage({ type: 'error', message: data.msg })
    }
  } catch {
    ElMessage.error('请求失败！')
  } finally {
    selectLoading.value = false
  }
}

// 订单发货
const handleDelete = async (row) => {
  row.loading = true
  try {
    const data = await axios.post('/bus/deliver/order', { id: row.id })
    if (data.code === 0) {
      // 删除成功
      ElMessage({
        type: 'success',
        message: data.msg
      })
      tableData.list = []
      // 重新获取商品列表
      getOrderList()
    } else {
      // 删除失败
      ElMessage({
        type: 'error',
        message: data.msg
      })
    }
  } catch (err) {
    ElMessage.error('请求失败！')
  } finally {
    row.loading = false
  }
}

// 提交筛选条件筛选订单数据
const submitFilter = async () => {
  // 创建请求参数
  // 验证商品货号是否正确
  if (orderNo.value !== '' && !/^[A-Z]{5}\d{15}/.test(orderNo.value)) {
    return ElMessage({
      type: 'error',
      message: '订单编号不正确，订单编号为5位大写字母加15位数字组合！'
    })
  }
  try {
    const data = await axios.get('/bus/filter/deal/order', {
      params: {
        orderNo: orderNo.value,
        nameOrPhone: nameOrPhone.value
      }
    })
    if (data.code === 0) {
      // 获取成功
      ElMessage({
        type: 'success',
        message: data.msg
      })
      // 对数据进行处理
      total.value = data.data.length
      currentPage.value = 1
      allOrderList = data.data
      tableData.list = []
      dealOrderData()
    } else {
      ElMessage({
        type: 'error',
        message: data.msg
      })
    }
  } catch {
    ElMessage.error('请求失败！')
  }
}
getOrderList()
</script>

<style lang="scss" scoped>
.goods-container {
  padding: 50px;

  .filter-content {
    padding: 15px;
    min-width: 1120px;
    border: 1px solid #e1e1e1;

    .filter-btn {
      display: flex;
      justify-content: space-between;

      .filter-title {
        span {
          margin-left: 5px;
        }
      }
    }
    .filter-form {
      margin-top: 15px;
      padding: 0 30px;
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
    }

    .filter-item {
      width: 26%;
      margin-bottom: 10px;

      div {
        display: flex;
        align-items: center;

        span {
          white-space: nowrap;
        }
      }
    }
  }
  .goods-title {
    padding: 15px;
    margin-top: 30px;
    min-width: 1120px;
    border: 1px solid #e1e1e1;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .goods-list {
    margin-top: 30px;
    min-width: 1120px;
    background-color: #fff;
    :deep(.el-table .el-table__cell) {
      text-align: center;
    }

    .pagination-container {
      margin-top: 15px;
      display: flex;
      justify-content: space-between;

      .option-container {
        display: flex;
        align-items: center;

        .btn {
          margin-left: 15px;
        }
      }
    }
  }
}
</style>
